import axios from 'axios';
import md5 from 'md5';
import config from '@/config/base.json';
import utils from '@/utils/index.js';
import qs from 'qs';

// axios请求配置
const CONFIG = {
  timeout: 15000,
  baseURL: config.baseUrl,
  headers: {
    post: {'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'},
    common: {'X-Requested-With': 'XMLHttpRequest'}
  },
  responseType: 'json',
  transformRequest: [function (data) {
    return qs.stringify(data.params);
  }]
};

export const fetch = axios.create(CONFIG);

// 请求拦截器
fetch.interceptors.request.use(config => {
  const appId = 'i-yi-yi-1182';
  const randStr = utils.randomString();
  const timeStamp = new Date().getTime();
  const safeToken = md5(`${appId}/${randStr}/${timeStamp}`);
  config.data.params = {
    ...utils.filterEmptyStr(config.data.params),
    appId,
    randStr,
    timeStamp,
    safeToken
  };
  return config;
}, error => Promise.reject(error));
